<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import navbar from "@/components/navbar/navbar.vue";
import { onPageScroll } from "@dcloudio/uni-app";
import { router, toast } from "@/utils/tools";
import { apiPublishGoods } from "@/apis/goods";
import { uploadImg } from "@/utils/request";
import { mapStores } from "pinia";
import { apiProductDict } from "@/apis/product";
import { onLoad } from "@dcloudio/uni-app";
import { useUserStore } from "@/stores/user";
import { onShow } from "@dcloudio/uni-app";
import { onReady } from "@dcloudio/uni-app";
import { apiComfirmOrder, wxPayMiniAppPay } from '@/apis/order';
import { getToken } from "@/utils/auth";
const bgImg = 'https://fuyue-test-oss.oss-cn-shanghai.aliyuncs.com/fee67d34-9269-428d-aa75-3b0f46879aac.png';
const userStore = useUserStore();
// 获取用户信息
const userMySelf = userStore.userInfo;
const criteriaId = ref()
const imgList = ref([]);
const navbarFixed = ref(false);
const showLoginRef = ref(false);
const chooseUploadRef = ref(false);
const showRef = ref(false);

const dictList = ref([]);

const dictFields = ref([]);
import cache from "@/utils/cache";
const chooseLocation = requirePlugin('chooseLocation');
//const key = ref("XMGBZ-I25WB-INDUT-JPNBT-ATY6S-YRBTJ");
const key = ref("QWQBZ-XIXCZ-6W2XR-7ISUU-QQX6E-GMBEF");
const referer = ref('乐石');
const category = ref('全部,地名地址,小区,酒店宾馆');
const latitude: any = ref(null);
const longitude: any = ref(null);
const fbAddress: any = ref('')
const data = reactive({
  formData: {
    describes: "", // 内容
    title: "", // 标题
    images: [], // 照片路径
    delivery: 0, // 发货方式  0-包邮 1-不包邮 2-自取
    oldPrice: "", // y原价
    currentPrice: "", // 现价
    types: "", // 类型
    brand: "", // 品牌
    fineness: "", // 成色
    address: "", // 详细地址
    lon: null,
    lat: null
  },
  clearFormData: {
    describes: "", // 内容
    title: "", // 标题
    images: [], // 照片路径
    delivery: "", // 发货方式  0-包邮 1-不包邮 2-自取
    oldPrice: "", // y原价
    currentPrice: "", // 现价
    types: "", // 类型
    brand: "", // 品牌
    fineness: "", // 成色
    address: "", // 详细地址
  },
  rules: {
    title: {
      type: "string",
      required: true,
      message: "请填写标题",
      trigger: ["blur", "change"],
    },
    describe: {
      type: "string",
      max: 1,
      required: true,
      message: "请填写描述",
      trigger: ["blur", "change"],
    },
  },
});
const formRef = ref(null);
const submit = () => {
  uni.showToast({
    title: "提交成功",
  });
};
const handleChooseUpload = () => {
  // 判断是否登录
  if (null === getToken()) {
    showLoginRef.value = true;
    return false;
  }
  chooseUploadRef.value = true;
};

const isLoginChange = () => {
  if (!uni.getStorageSync("token")) {
    uni.navigateTo({
      url: "/pages/login/login",
    });
    return true;
  }
  return false;
};

const handleUploadImage = () => {
  uni.chooseImage({
    count: 9,
    sizeType: ["original", "compressed"],
    sourceType: ["album"],
    success: (imgRes: any) => {
      uni.showLoading({ title: "上传中..." });
      let files = imgRes.tempFiles;
      files.forEach(async (item: any, index: number) => {
        let resUpload = await uploadImg(item.path);
        // 这里可以进行上传操作
        imgList.value.push({
          type: "image",
          url: resUpload.data.url,
        });
      });
      uni.hideLoading();
    },
  });
};

const handleUploadVideo = async () => {
  uni.chooseVideo({
    sourceType: ["camera", "album"],
    compressed: true, // 需要压缩
    maxDuration: 60,
    success: async function (res) {
      uni.showLoading({ title: "上传中..." });
      if (res.size > 1024 * 1024 * 10) {
        toast("视频过大请重新上传！");
      }
      // 上传缩略图
      // 上传视频
      let resVideoUpload = await uploadImg(res.tempFilePath);
      imgList.value.push({
        type: "video",
        url: resVideoUpload.data.url,
        thumb: res.thumbTempFilePath,
      });
      uni.hideLoading();
    },
  });
};

const handleClose = (index: number = 0) => {
  // 删除一个元素
  imgList.value.splice(index, 1);
};
// const chooseLocation = () => {
//   toast("选择位置");
// };
const shoppingId = ref()
const num = ref()
const price = ref()
const comfirmOrder = async () => {
  let params = {
    commodityId: null, //商品ID
    commodityName: null, //商品的标题名称
    actualPayment: null, //支付价格
    userAddressId: null, //发货地址ID
    type: 4, //消费类型  0-开会员  1-开商铺  2-购买商品  3-藏品认证  4-评价费用
    activitiesId: criteriaId.value, //评选活动Id
    appCommodityList: [data.formData], // 4评价活动的时候传
    collectionCertificationList: null // 3藏品认证的时候传
  };
  // let res = await apiComfirmOrder(params);
  // if (res.code == 200) {
  //     shoppingId.value = res.data.shopingId
  //     num.value =res.data.num
  //     price.value =res.data.price
  //     wxPayMiniAppPayFn()
  // }
  await wxPayMiniAppPayFn(params)
}
const wxPayMiniAppPayFn = async (params: any) => {
  let res = await wxPayMiniAppPay(params)
  if (res.code == 200) {
    if (res.code == 200) {
      let dataObj = res.data;
      wx.openEmbeddedMiniProgram({
        appId: dataObj.appId,
        path: dataObj.path,
        envVersion: 'release',//正常跳转路径
        success(res) {
          uni.setStorageSync('isPaySuccess', true)
        }
      })
    }
  }
}
const cancelClick = () => {
  data.formData = {
    describes: "", // 内容
    title: "", // 标题
    images: [], // 照片路径
    delivery: "", // 发货方式  0-包邮 1-不包邮 2-自取
    oldPrice: "", // y原价
    currentPrice: "", // 现价
    types: "", // 类型
    brand: "", // 品牌
    fineness: "", // 成色
    address: "", // 详细地址
  };
  imgList.value = [];
};
const publishGoods = async () => {
  if (isLoginChange()) return;

  if (false === userStore.isLogin) {
    showLoginRef.value = true;
    return false;
  }

  if (!data.formData.title) {
    toast("请填写标题！");
    return false;
  }

  if (!data.formData.describes) {
    toast("请填写简介！");
    return false;
  }
  if (imgList.value.length <= 0) {
    toast("请上传图片！");
    return false;
  }
  if (data.formData.delivery === "") {
    toast("请选择发货方式！");
    return false;
  }
  if (!data.formData.oldPrice) {
    toast("请填写原价！");
    return false;
  }
  if (!data.formData.currentPrice) {
    toast("请填写价格！");
    return false;
  }
  // if (!userMySelf.shopVip) {
  //   return toast("暂未开通会员或者商铺！");
  // }
  let fieldData = [];
  // 处理字典数据
  for (const key1 in dictFields.value) {
    for (const key2 in dictList.value) {
      for (const key3 in dictList.value[key2]["types"]) {
        if (
          data.formData[dictFields.value[key1]] ==
          dictList.value[key2]["types"][key3]["typeId"]
        ) {
          let field = {
            field: dictFields.value[key1],
            fieldName: dictList.value[key2]["deptName"],
            value: data.formData[dictFields.value[key1]],
            name: dictList.value[key2]["types"][key3]["deptName"],
          };
          fieldData.push(field);
        }
      }
    }
  }
  let images: any[] = [];
  for (const key in imgList.value) {
    images.push(imgList.value[key]["url"]);
  }
  data.formData.images = images.join(",");
  data.formData.dict = JSON.stringify(fieldData);
  // 防抖 500毫秒
  uni.$uv.debounce(add, 500);
};

const add = async () => {
  await comfirmOrder()
};

const getDictList = async () => {
  let res = await apiProductDict({});
  dictList.value = res.data;
  for (const key in dictList.value) {
    dictFields.value.push(dictList.value[key]["field"]);
  }
};
// 监听页面滚动
onPageScroll((e: any) => {

});

onLoad((options: any) => {
  criteriaId.value = options.id
  // 未登录
  if (null === getToken()) {
    showLoginRef.value = true;
  }
  getDictList();
});

onShow(() => {
  fetchData()
});
// 地图选点
const choosePosition = async () => {
  const location = JSON.stringify({
    latitude: latitude.value,
    longitude: longitude.value
  });
  uni.navigateTo({
    url: `plugin://chooseLocation/index?key=${key.value}&referer=${referer.value}&location=${location}&category=${category.value}`
  });
}
const getChooseLocation = async () => {
  await choosePosition()
}
const fetchData = async () => {
  chooseLocationFn()
  const res = await chooseLocation.getLocation();
  if (res) {
    fbAddress.value = res.address
    data.formData.address = res.address;
    data.formData.lon = res.longitude
    data.formData.lat = res.latitude
    longitude.value = res.longitude;
    latitude.value = res.latitude;
    cache.set("address", res.address);
  }
}
const chooseLocationFn = async () => {
  uni.getLocation({
    type: 'wgs84',
    success: (res) => {
      latitude.value = res.latitude
      longitude.value = res.longitude
    }
  })
}
onMounted(() => { });
</script>

<template>
  <!-- <navbar :fixed="navbarFixed" :back="true" title="评选上架" /> -->
  <view class="container">
    <input class="form-input-item form-input-bg" v-model="data.formData.title" border="none" placeholder="请输入奇石描述标题~" />

    <textarea v-model="data.formData.describes" class="form-textarea-item form-input-bg" placeholder="请详细描述奇石信息~" />

    <view class="form-upload-card form-input-bg">
      <view class="form-upload-item">
        <text> 奇石图片 </text>
      </view>
      <uv-line length="100%" color="#CECECE"></uv-line>
      <view class="form-upload">
        <view class="form-upload-img">
          <view v-for="(item, index) in imgList" :key="index" class="image">
            <image v-if="item.type == 'image'" :src="item.url" mode="scaleToFill" />
            <video v-else :src="item.url" :poster="item.thumb" />
            <view class="close flex flex-center" @click="handleClose(index)">
              <view class="close-line"></view>
            </view>
          </view>
          <view class="upload-btn-bg image" @click="handleChooseUpload" v-if="imgList.length < 9">
            <image class="icon-plus" src="@/static/images/plus.png" mode="scaleToFill" />
            <text class="upload-btn-text">添加图片</text>
          </view>
        </view>
      </view>
      <view class="form-card">
        <view class="form-card-title">
          <text>类型 / 种类</text>
        </view>
        <uv-line length="100%" color="#CECECE"></uv-line>
        <view class="form-card-title">
          <view v-for="item in dictList" :key="item.typeId">
            <view class="form-card-radio">
              <view class="form-radio-title">
                <text>{{ item.deptName }}:</text>
              </view>
              <uv-radio-group v-model="data.formData[item.field]">
                <uv-radio :label="typesItem.deptName" :name="typesItem.typeId" v-for="typesItem in item.types"
                  :key="typesItem.typeId"></uv-radio>
              </uv-radio-group>
            </view>
            <view class="line"></view>
          </view>
        </view>
      </view>
      <view class="form-card form-item">
        <view class="form-item-label">
          <image src="@/static/images/orientation.png" mode="scaleToFill" class="form-item-icon" />
          <text>宝贝位置：</text>
        </view>
        <view class="form-input" @click="getChooseLocation">
          <input placeholder="请选择" disabled v-model="data.formData.address" />
          <view class="form-input-suff">
            <image src="@/static/images/arrow.png" />
          </view>
        </view>
      </view>
      <view class="form-card form-item" style="margin-bottom: 0">
        <view class="form-item-label">
          <image src="@/static/images/money.png" mode="scaleToFill" class="form-item-icon" />
          <text>宝贝价格：</text>
        </view>
        <view class="form-input">
          <uv-input type="digit" class="form-input" placeholder="请输入宝贝价格" border="none"
            v-model="data.formData.currentPrice"></uv-input>
          <view class="form-input-suff">
            <text>单位：元</text>
          </view>
        </view>
      </view>
      <view class="line" style="margin: 0"></view>
      <view class="form-card form-item">
        <view class="form-item-label">
          <image src="@/static/images/money-origin.png" mode="scaleToFill" class="form-item-icon" />
          <text>宝贝原价：</text>
        </view>
        <view class="form-input">
          <uv-input type="digit" class="form-input" placeholder="请输入宝贝原价" border="none"
            v-model="data.formData.oldPrice"></uv-input>
          <view class="form-input-suff">
            <text>单位：元</text>
          </view>
        </view>
      </view>
    </view>
    <view class="form-card form-item">
      <view class="form-item-label">
        <image src="@/static/images/delivery.png" mode="scaleToFill" class="form-item-icon" />
        <text>发货方式：</text>
      </view>
      <uv-radio-group v-model="data.formData.delivery">
        <uv-radio label="包邮" :name="0"></uv-radio>
        <uv-radio label="不包邮" :name="1"></uv-radio>
        <uv-radio label="自取" :name="2"></uv-radio>
      </uv-radio-group>
    </view>

    <view class="btn-group justify-between">
      <button class="btn-cancel" @click="cancelClick">取消</button>
      <button class="btn-publish" @click="publishGoods">缴费并上架</button>
    </view>
  </view>

  <!-- <uv-overlay
    zIndex="1999"
    :show="showLoginRef"
    zoom="true"
    round="10"
    @change="change"
    class="overlay"
  >
    <view class="validate">
      <view class="flex justify-between">
        <view class="icon flex flex-center">
          <view class="icon2 flex flex-center">
            <image
              src="@/static/images/alarm-warning-line.png"
              mode="scaleToFill"
            />
          </view>
        </view>
        <view class="icons-close" @click="showLoginRef = false">
          <image src="@/static/images/icons-close.png" mode="scaleToFill" />
        </view>
      </view>
      <view class="title"> 登录提醒 </view>
      <view class="content"
        >该功能需要您的用户信息方能正常使用，请先完成登录~
      </view>
      <view class="flex justify-around btn-group">
        <button class="btn-cancel" @click="showLoginRef = false">取消</button>
        <button class="btn-open" @click="router(`/pages/login/login`)">
          立即登录
        </button>
      </view>
      <view class="form-card form-item">
        <view class="form-item-label">
          <image
            src="@/static/images/delivery.png"
            mode="scaleToFill"
            class="form-item-icon"
          />
          <text>发货方式：</text>
        </view>
        <uv-radio-group v-model="data.formData.delivery">
          <uv-radio label="包邮" :name="0"></uv-radio>
          <uv-radio label="不包邮" :name="1"></uv-radio>
          <uv-radio label="自取" :name="2"></uv-radio>
        </uv-radio-group>
      </view>

      <view class="btn-group justify-between">
        <button class="btn-cancel" @click="cancelClick">取消</button>
        <button class="btn-publish" @click="publishGoods">缴费并上架</button>
      </view>
    </view>
  </uv-overlay> -->

  <!-- <uv-overlay
    zIndex="1999"
    :show="showLoginRef"
    zoom="true"
    round="10"
    @change="change"
    class="overlay"
  >
    <view class="validate">
      <view class="flex justify-between">
        <view class="icon flex flex-center">
          <view class="icon2 flex flex-center">
            <image
              src="@/static/images/alarm-warning-line.png"
              mode="scaleToFill"
            />
          </view>
        </view>
        <view class="icons-close" @click="showLoginRef = false">
          <image src="@/static/images/icons-close.png" mode="scaleToFill" />
        </view>
      </view>
      <view class="title"> 登录提醒 </view>
      <view class="content"
        >该功能需要您的用户信息方能正常使用，请先完成登录~
      </view>
      <view class="flex justify-around btn-group">
        <button class="btn-cancel" @click="showLoginRef = false">取消</button>
        <button class="btn-open" @click="router(`/pages/login/login`)">
          立即登录
        </button>
      </view>
    </view>
  </uv-overlay> -->
  <!-- 文件选择器 -->
  <uv-overlay :show="chooseUploadRef" @click="chooseUploadRef = false">
    <view class="choose flex flex-column flex-center">
      <view @click="handleUploadImage">选择图片</view>
      <view class="line">
        <uv-line></uv-line>
      </view>
      <view @click="handleUploadVideo">选择视频</view>
    </view>
  </uv-overlay>
  <!-- 文件选择器 -->
  <uv-overlay :show="chooseUploadRef" @click="chooseUploadRef = false">
    <view class="choose flex flex-column flex-center">
      <view @click="handleUploadImage">选择照片</view>
      <view class="line">
        <uv-line></uv-line>
      </view>
      <view @click="handleUploadVideo">选择视频</view>
    </view>
  </uv-overlay>
</template>

<style lang="scss" scoped>
::v-deep .uv-radio {
  margin: 10rpx;
}

::v-deeep .uv-overlay {
  width: auto !important;
}

::v-deep .uv-navbar__content__left {
  display: none !important;
}

.choose {
  border-radius: 10px 10px 0 0;
  position: absolute;
  bottom: 0;
  width: 100%;
  background-color: #ffffff;
  height: 150rpx;

  .line {
    margin: 10rpx 0;
    width: 100%;
  }
}

.container {
  position: relative;
  margin-top: 20rpx;
  font-size: 28rpx;

  .form-input-item {
    margin-bottom: 30rpx;
    height: 100rpx;
    padding-left: 20rpx;
  }

  textarea {
    padding: 0 20rpx;
    box-sizing: border-box;
  }

  .form-textarea-item {
    position: static;
    height: 200rpx;
    padding-top: 20rpx;
    margin-bottom: 30rpx;
  }

  .form-input-bg {
    background-color: #ffffff;
    border-radius: 24rpx;
    width: 100%;
  }

  .form-upload-card {
    height: 100%;
    margin-bottom: 30rpx;

    .form-upload-item {
      padding: 20rpx;
    }

    .form-upload {
      padding: 20rpx;
      display: flex;
      height: 100%;

      .form-upload-img {
        flex-wrap: wrap;
        height: 100%;
        display: flex;
      }

      .image {
        position: relative;
        width: 144rpx;
        height: 144rpx;
        margin-right: 30rpx;
        margin-bottom: 30rpx;

        video {
          width: 100%;
          height: 100%;
        }

        image {
          border-radius: 6px;
        }

        .close {
          position: absolute;
          right: -10rpx;
          top: -10rpx;
          background-color: #f3604e;
          width: 18px;
          height: 18px;
          border-radius: 50%;

          .close-line {
            background-color: #ffffff;
            height: 2px;
            width: 12px;
            border-radius: 1px;
          }
        }

        .icon-plus {
          width: 48rpx;
          height: 48rpx;
        }
      }

      .upload-btn-bg {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background-color: #efefef;
      }

      .upload-btn-text {
        color: #cecece;
        font-size: 24rpx;
      }
    }
  }

  .form-card {
    width: 100%;
    background-color: #ffffff;
    border-radius: 24rpx;
    margin-bottom: 20rpx;

    .form-card-title {
      color: #333333;
      padding: 20rpx;
    }

    .form-card-radio {
      display: flex;
    }
  }
}

.form-radio-title {
  margin-top: 10rpx;
  font-size: 28rpx;
}

.form-radio-group {
  padding-right: 30rpx;
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.form-radio-item {
  display: flex;
  align-items: center;

  .form-radio-label {
    font-size: 25rpx;
  }
}

.form-input {
  border: none;
  font-size: 26rpx;
  position: relative;
  width: 100%;
  flex: 1;

  .form-input-suff {
    position: absolute;
    right: 0;
    transform: translate(-50%, -50%);
    top: 50%;

    text {
      font-size: 24rpx;
      color: #bebebe;
    }

    image {
      width: 28rpx;
      height: 28rpx;
    }
  }
}

.btn-group {
  display: flex;
  padding-bottom: 60rpx;
  margin-top: 50rpx;
  font-size: 28rpx;

  .btn-cancel {
    background-color: transparent;
    border: 1px solid #999999;
    box-shadow: none;
    border-radius: 24rpx;
    width: 220rpx;
    height: 100rpx;
  }

  .btn-publish {
    background: linear-gradient(0deg,
        rgba(191, 1, 3, 1) 0%,
        rgba(255, 84, 2, 1) 99.2%);
    box-shadow: none;
    border: 1px solid #999999;
    border-radius: 24rpx;
    border: none;
    width: 420rpx;
    color: #ffffff;
    height: 100rpx;
  }
}

.line {
  margin: 0;
  border-bottom-width: 1px;
  border-bottom-style: solid;
  transform: scaleY(0.5);
  border-color: #cecece;
  margin: 10px;
}

.form-item {
  display: flex;
  height: 100rpx;
  align-items: center;
}

.form-item-label {
  display: flex;
  flex-direction: row;
  justify-content: flex-start; // 靠左对齐
  flex-wrap: nowrap;

  text {
    font-size: 28rpx;
  }
}

.form-item-icon {
  margin-top: 7rpx;
  width: 32rpx;
  height: 32rpx;
  margin: 0 20rpx;
}

.validate {
  padding: 40rpx;
  position: absolute;
  border-radius: 20rpx;
  width: 626rpx;
  height: 500rpx;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  background-color: #ffffff;

  .icons-close {
    width: 50rpx;
    height: 50rpx;
  }

  .btn-group {
    margin-top: 40rpx;

    .btn-cancel {
      border-radius: 8px;
      border: 1px solid rgba(154, 154, 154);
      font-size: 14px;
      width: 250rpx;
      color: #4f4f4f;
      height: 80rpx;
    }

    .btn-open {
      border-radius: 8px;
      background: linear-gradient(0deg, #bf0103, #ff5402);

      color: #ffffff;
      border: 0px solid #bbbbbb;
      font-size: 14px;
      width: 250rpx;
      height: 80rpx;
    }
  }

  .icon {
    margin-bottom: 20rpx;
    width: 114rpx;
    height: 114rpx;
    border-radius: 50%;
    background-color: #fef3f2;

    .icon2 {
      width: 81rpx;
      height: 81rpx;
      border-radius: 50%;
      background-color: #fee4e2;
    }

    image {
      width: 48rpx;
      height: 48rpx;
    }
  }

  .title {
    font-size: 32rpx;
    font-weight: 700;
    margin-bottom: 20rpx;
  }

  .content {
    color: #6c6c6c;
    font-size: 28rpx;
  }
}
</style>
